import { CartItem } from "@/types/cart";
import { IApiRes } from "@/types/data";
import request from "@/utils/request";
import { defineStore } from "pinia";
import user from "./user";

const useCartStore = defineStore('cart', {
  // 状态
  state() {
    return {
      list: [] as CartItem[] // 购物车数组
    }
  },
  // 数据持久化
  persist: {
    enabled: true,
    strategies: [{key:'rabbit-cart-76'}]
    // key: 'category'
  },
  // 计算
  getters: {
    // 有效商品
    effectiveList(): CartItem[] {
      return this.list.filter(item => item.isEffective)
    },
    // 有效商品总数
    effectiveListCounts(): number {
      return this.effectiveList.reduce((sum: number, item: CartItem) => {
        return sum + item.count
      }, 0)
    },
    // 有效商品总价格
    effectiveListPrice(): number {
      return this.effectiveList.reduce((sum: number, item: CartItem) => {
        return sum + item.count * +item.nowPrice
      }, 0)
    },
    // 全选计算
    isAllSelected(): boolean  {
      return this.effectiveList.every(item => item.selected)
    },
    // 选中的商品
    selectedList(): CartItem[] {
      return this.effectiveList.filter(item => item.selected)
    },
    // 选择的数量
    selectedListCounts(): number {
      return this.selectedList.reduce((sum, item) => {
        return sum + item.count
      }, 0)
    },
    // 选择商品总价格
    selectedListPrice(): number {
      return this.selectedList.reduce((sum, item) => {
        return sum + item.count * +item.price
      }, 0)
    },
    // 登录状态
    isLogin(): boolean {
      const  use  = user()
      return !!use.profile.token
    }
  },
  // 方法
  actions: {
    // 添加购物车
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', data)
        // 重新获取购物车数据
        this.getCartList()
      } else {
        const g = this.list.find(item => item.skuId === data.skuId)
        if (g) {
          g.count += data.count
        } else {
          this.list.push(data)
        }
      }
    },
    // 购物车数据
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<IApiRes<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        this.list.forEach(async (item) => {
          const { skuId } = item
          // 根据 skuId 获取最新商品信息
          const res = await request.get<IApiRes<CartItem>>(`/goods/stock/${skuId}`)
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          item.nowPrice = lastCartInfo.nowPrice
          // 更新商品库存
          item.stock = lastCartInfo.stock
          // 更新商品是否有效
          item.isEffective = lastCartInfo.isEffective
        })
      }
    },
    // 删除购物车数据
    async delCart(skuIds: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {data: { ids: skuIds }})
        // 重新获取购物车数据
        this.getCartList()
      } else {
        // 要删除的skuIds: ['300289261', 'abcdafdadsfds', 'a']
        // 要留下来的条件是：list中的商品的skuId 不在 数组skuIds中
        this.list = this.list.filter(it => {
          return skuIds.includes(it.skuId) === false
        })
      }
    },
    // 修改购物车商品
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        const goods = this.effectiveList.find((item) => item.skuId === skuId)
        if (data.selected !== undefined) {
          goods!.selected = data.selected
        }
        if (data.count !== undefined) {
          goods!.count = data.count
        }
      }
    },
    // 修改全选或者全不选
    async updateCartAllSelected(isSelected: boolean) {
      if (this.isLogin) {
        await request.put('/member/cart/selected', {
          selected: isSelected,
        })
        // 获取购物车列表
        this.getCartList()
      } else {
        this.list.forEach(item => item.selected = isSelected)
      }
    },
    // 清空购物车
    clearCart() {
      // 退出登录需清空购物车
      this.list = []
    },
    // 合并购物车
    async mergeLocalCart() {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  }
});

export default useCartStore;